package com.bbseguros.pesquisador.util;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

import org.apache.log4j.Logger;

import com.bbseguros.pesquisador.bean.RelatorioOperacionalBean;
import com.bbseguros.pesquisador.bean.UserBean;
import com.bbseguros.pesquisador.mail.EmailThreadSender;

public class Util {

	private static final int MAX_VALUE = 999999;
	private static Logger logger = Logger.getLogger(Util.class);
	
	public static int generateRandomNumber() {
		Random random = new Random();
		int pick = random.nextInt(MAX_VALUE);
		return pick;
	}

	public static String transformFileName(int randomNumber) {
		char[] letters = new char[]{'a','b','c','d','e','f','g','h','i','j'};
		String number = String.valueOf(randomNumber);
		
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < number.length(); i++) {
			int l = Integer.parseInt(String.valueOf(number.charAt(i)));
			sb.append(letters[l]);
		}
		return sb.toString();
	}
	
	public static void sendMail (UserBean bean) {
		EmailThreadSender t = new EmailThreadSender(bean);
		t.start();
	}
	
	public static String readFile(File inputFile){
		BufferedInputStream input = null;
		ByteArrayOutputStream output = null;

		try {
			input = new BufferedInputStream(new FileInputStream(inputFile));
			int contentLength = input.available();

			output = new ByteArrayOutputStream();

			while (contentLength-- > 0) {
				output.write(input.read());
			}
			output.flush();
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		} finally {
			if (input != null) {
				try {
					input.close();
				} catch (IOException e) {
					logger.error(e.getMessage(), e);
				}
			}
			if (output != null) {
				try {
					output.close();
				} catch (IOException e) {
					logger.error(e.getMessage(), e);
				}
			}
		}
		return new String(output.toByteArray());
	}
	
	/**
	 * @param listBean
	 * @return
	 */
	public static String generateCSVSimpleBuffer( List<RelatorioOperacionalBean> listBean){
		StringBuffer buffer = new StringBuffer();
		
		buffer.append("Data");
		buffer.append(",");
		buffer.append("TT. Agendamentos");
		buffer.append(",");
		buffer.append("Qtd. Ag. Criticados");
		buffer.append(",");
		buffer.append("% Ag. Criticados");
		buffer.append("\n");
		
		RelatorioOperacionalBean bean = null;
		Iterator <RelatorioOperacionalBean> it = listBean.iterator();
		
		while (it.hasNext()) {
			bean = it.next();
			
			buffer.append(bean.getDate());
			buffer.append(",");
			buffer.append(bean.getTotal_search());
			buffer.append(",");
			buffer.append(bean.getCriticizedRecords());
			buffer.append(",");
			buffer.append(bean.getPercent());
			buffer.append("\n");
		}
		
		return buffer.toString();
	}
	
	public static String nullToBlanks(String value) {
		if(value==null) {
			value = "";
		}
		return value;
	}
	
	
	/**
	 * @param monitoramentos
	 * @return
	 */
	public static String convertExcel(List<String> monitoramentos){
		String header = "";
		
		header = header +"\"Codigo Pesquisador\",";
		header = header +"\"Recibo\",";
		header = header +"\"Data Recebimento\",";		
		header = header +"\"MSG Error\",";
		header = header +"\"Nome Cliente\",";
		header = header +"\"CPF/CNPJ\",";
		header = header +"\"CORRENTISTA BB?\",";
		header = header +"\"CLIENTE BV?\",";
		header = header +"\"DDD Residencial\",";
		header = header +"\"No. Fone Residencial\",";
		header = header +"\"DDD Comercial\",";
		header = header +"\"No. Fone Comercial\",";
		header = header +"\"DDD Celular\",";
		header = header +"\"No. Fone Celular\",";
		header = header +"\"E-mail\",";
		header = header +"\"Quer Receber SMS?\",";
		header = header +"\"Origem\",";
		header = header +"\"Codigo Frota\",";
		header = header +"\"Worksite\",";
		header = header +"\"Codigo Acao\",";
		header = header +"\"Codigo Local\",";
		header = header +"\"Codigo Forma\",";
		header = header +"\"Imei\",";		
		header = header +"\"Msisdn\",";		
		header = header +"\"Version\",";		
		header = header +"\"Marca Tipo\",";
		header = header +"\"Marca Veiculo\",";
		header = header +"\"Ano Veiculo\",";
		header = header +"\"Vencimento\",";
		header = header +"\"Marca Tipo\",";
		header = header +"\"Marca Veiculo\",";
		header = header +"\"Ano Veiculo\",";
		header = header +"\"Vencimento\",";
		header = header +"\"Marca Tipo\",";
		header = header +"\"Marca Veiculo\",";
		header = header +"\"Ano Veiculo\",";
		header = header +"\"Vencimento\"\n";
		
		StringBuffer sb = new StringBuffer(header);
		try{
			for (int i = 0; i < monitoramentos.size(); i++) {
				sb.append(splitValueData(monitoramentos.get(i)));
			}
			
		} catch(Exception ex) {
			ex.printStackTrace();
		}
		return sb.toString();
	}
	
	/**
	 * @param value
	 * @return
	 */
	private static String splitValueData(String value){
		String ret = "";
		String temp_codpesquisador = "";
		String temp_recibo = "";
		String temp_dtrecebimento = "";
		String temp_result = "";		
		String temp_status = "";
		String temp_msg_error = "";
		int pos1 = -1, pos2 = -1;
		
		pos1 = 0;
		pos2 = value.indexOf(",");
		temp_codpesquisador = value.substring(pos1+1, pos2-1);
		
		pos1 = pos2+1;
		pos2 = value.indexOf(",", pos1);
		temp_recibo = value.substring(pos1+1, pos2-1);
		
		pos1 = pos2+1;
		pos2 = value.indexOf(",", pos1);
		temp_dtrecebimento = value.substring(pos1+1, pos2-1);
		
		pos1 = pos2+1;
		pos2 = value.indexOf(",", pos1);
		temp_result = value.substring(pos1+1, pos2-1);

		pos1 = pos2+1;
		pos2 = value.indexOf(",", pos1);
		temp_status = value.substring(pos1+1, pos2);
		
		pos1 = pos2+1;
		pos2 = value.indexOf(",", pos1);
		temp_msg_error = value.substring(pos1+1, value.length()-1);
		
		
		ret = ret +"\""+temp_codpesquisador+"\",";
		ret = ret +"\""+temp_recibo+"\",";
		ret = ret +"\""+temp_dtrecebimento+"\",";
		ret = ret +"\""+temp_msg_error+"\",";
		ret = ret +"\""+getValueXml("NOME_CLIENTE", temp_result, 0)+"\",";
		ret = ret +"\""+getValueXml("CPFCNPJ", temp_result, 0)+"\",";
		ret = ret +"\""+getValueXml("CORRENTISTA_BB", temp_result, 0)+"\",";
		ret = ret +"\""+getValueXml("CLIENTE_BV", temp_result, 0)+"\",";
		ret = ret +"\""+getValueXml("DDD_RES", temp_result, 0)+"\",";
		ret = ret +"\""+getValueXml("NR_FONE_RES", temp_result, 0)+"\",";
		ret = ret +"\""+getValueXml("DDD_COM", temp_result, 0)+"\",";
		ret = ret +"\""+getValueXml("NR_FONE_COM", temp_result, 0)+"\",";
		ret = ret +"\""+getValueXml("DDD_CEL", temp_result, 0)+"\",";
		ret = ret +"\""+getValueXml("NR_FONE_CEL", temp_result, 0)+"\",";
		ret = ret +"\""+getValueXml("EMAIL", temp_result, 0)+"\",";
		ret = ret +"\""+getValueXml("RECEBE_SMS", temp_result, 0)+"\",";
		ret = ret +"\""+getValueXml("ORIGEM", temp_result, 0)+"\",";
		ret = ret +"\""+getValueXml("COD_FROTA", temp_result, 0)+"\",";
		ret = ret +"\""+getValueXml("FLAG_WORKSITE", temp_result, 0)+"\",";
		ret = ret +"\""+getValueXml("COD_ACAO", temp_result, 0)+"\",";
		ret = ret +"\""+getValueXml("COD_LOCAL", temp_result, 0)+"\",";
		ret = ret +"\""+getValueXml("COD_FORMA", temp_result, 0)+"\",";
		ret = ret +"\""+getValueXml("IMEI", temp_result, 0)+"\",";
		ret = ret +"\""+getValueXml("MSISDN", temp_result, 0)+"\",";
		ret = ret +"\""+getValueXml("VERSION", temp_result, 0)+"\",";
		ret = ret +"\""+getValueXml("COD_MARCA_TIPO", temp_result, 1)+"\",";
		ret = ret +"\""+getValueXml("MARCAVEICULO", temp_result, 1)+"\",";
		ret = ret +"\""+getValueXml("ANOVEICULO", temp_result, 1)+"\",";
		ret = ret +"\""+getValueXml("VENCIMENTO", temp_result, 1)+"\",";
		ret = ret +"\""+getValueXml("COD_MARCA_TIPO", temp_result, 2)+"\",";
		ret = ret +"\""+getValueXml("MARCAVEICULO", temp_result, 2)+"\",";
		ret = ret +"\""+getValueXml("ANOVEICULO", temp_result, 2)+"\",";
		ret = ret +"\""+getValueXml("VENCIMENTO", temp_result, 2)+"\",";
		ret = ret +"\""+getValueXml("COD_MARCA_TIPO", temp_result, 3)+"\",";
		ret = ret +"\""+getValueXml("MARCAVEICULO", temp_result, 3)+"\",";
		ret = ret +"\""+getValueXml("ANOVEICULO", temp_result, 3)+"\",";
		ret = ret +"\""+getValueXml("VENCIMENTO", temp_result, 3)+"\"\n";
			
		return ret;
	}
	
	/**
	 * @param search
	 * @param buff
	 * @param index
	 * @return
	 */
	private static String getValueXml(String search, String buff, int index){
		String ret = "";
		
		String flag1 = "<"+search+">";
		String flag2 = "</"+search+">";
		int pos1 = -1, pos2 = -1;
		
		if (index > 0) {
			for (int i = 0; i < index; i++){
				
				if (pos2 > -1){
					pos1 = buff.indexOf(flag1, pos2+flag2.length());
					
				}else {
					pos1 = buff.indexOf(flag1);
				}				
				pos2 = buff.indexOf(flag2, pos1);				
			}
		}
		else{
			pos1 = buff.indexOf(flag1);
			pos2 = buff.indexOf(flag2);
		}
		
		if ( (pos1 > -1) && (pos2 > -2)){
			ret = buff.substring(pos1+flag1.length(), pos2);
		}
		
		return ret;
	}

}
